import { COMMON_CONFIG } from '@/app.contants';
import Taro from '@tarojs/taro';
import commonStore from '../store/common';

async function request(options: any = { method: 'GET', data: {} }) {
  if (!COMMON_CONFIG.NO_CONSOLE) {
    console.log(`${new Date().toLocaleString()}【M=${options.method}】【U=${options.url}】【P=${JSON.stringify(options.data)}】`);
  }
  const res = await Taro.request({
    url: COMMON_CONFIG.BASE_URL + options.url,
    data: {
      ...options.data,
    },
    header: {
      ...commonStore.header(),
      'Content-Type': 'application/json',
    },
    method: options.method,
  });
  const { statusCode, data } = res;
  if (statusCode >= 200 && statusCode < 300) {
    if (!COMMON_CONFIG.NO_CONSOLE) {
      console.log(`${new Date().toLocaleString()}【U=${options.url}】【接口响应:】`, res.data);
    }
    if (parseInt(data.code) !== 200) {
      Taro.showToast({
        title: `${data.msg}~` || data.code,
        icon: 'none',
        mask: true,
      });
    }
    return data;
  } else {
    throw new Error(`网络请求错误，状态码${statusCode}`);
  }
}

export default {
  get: (url: string) => {
    return request({ url: url, method: 'GET' });
  },
  put: (url: string, data: any) => {
    return request({ url: url, method: 'PUT', data });
  },
  post: (url: string, data: any) => {
    return request({ url: url, method: 'POST', data });
  },
  del: (url: string, data: any) => {
    return request({ url: url, method: 'DELETE', data });
  },
};
